package com.hejiale.lease.web.app.interceptor;

import com.hejiale.lease.common.exception.LeaseException;
import com.hejiale.lease.common.result.ResultCodeEnum;
import com.hejiale.lease.common.threadlocal.LoginThreadLocalHolder;
import com.hejiale.lease.common.utils.JwtUtil;
import com.hejiale.lease.model.entity.LoginUser;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @description: 拦截器，用于验证token
 * @author: HeJiale
 * @since 2025/3/25 上午10:33
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    /**
     * 拦截器，在请求处理之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("access-token");

        if (token == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);
        }

        Claims claims = JwtUtil.parseToken(token);

        LoginThreadLocalHolder.setLoginUser(LoginUser.builder()
                .userId(claims.get("userId", Long.class))
                .username(claims.get("username", String.class))
                .build());

        return true;
    }

    /**
     * 清除threadLocal
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginThreadLocalHolder.clear();
    }
}
